package com.green.common.util;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.green.common.weibo4j.org.json.JSONArray;
import com.green.common.weibo4j.org.json.JSONException;
import com.green.common.weibo4j.org.json.JSONObject;

/**
 * 此版本使用document 对象封装XML， 解决发送短信内容包涵特殊字符而出现无法解析， 如 短信为：“你好，<%&*&*&><<<>fds 测试短信”
 * 
 * @author 8373
 */
public class HttpXmlUtil {
	// ############################此部分参数需要修改
	public static String userName = "dh20634"; // 接口账号
	public static String password = "20634sh"; // 密码
	// public static String phone = "18676665381"; // 要发送的手机号码
	// public static String content = "新端口测试短信"; // 短信内容
	public static String sign = "【世华经纪】"; // 短信签名，该签名必须提前报备
	// public static String msgid = "85a75b4256184f3292f772410a1f808f"; //
	// 自定义msgid
	public static String subcode = ""; // 扩展字号
	public static String sendtime = ""; // 定时发送时间，时间格式201305051230
	public static String url = "http://3tong.net"; // 无限通使用地址

	// public static String url="http://www.10690300.com"; //三网通使用地址
	// ############################此部分参数需要修改

	/*
	 * public static void main(String[] args) { // 发送短信
	 * //System.out.println("*************发送短信*************");
	 * //send("136f1d3a-12bf-4c2c-b759-42ea59aa4848"
	 * ,"18676665381","尊敬的客户：车公庙地铁站顶级商铺，2万/平."); // 获取状态报告
	 * //System.out.println("*************状态报告*************");
	 * //System.out.println("#########:"+getReport().get("result")); //List
	 * list=(List)getReport().get("reportList");
	 * //System.out.println("*********:"+list.size());
	 * 
	 * // 获取上行 //System.out.println("*************获取上行*************");
	 * //getSms(); // 获取余额
	 * //System.out.println("*************获取余额*************"); //getBalance();
	 * Map map=send("asp123ww6733","18676665381","尊敬的用户，你使用的优惠套餐已更新，法轮功请及时查看！");
	 * 
	 * System.out.println(map.get("result"));
	 * 
	 * System.out.println(map.get("desc"));
	 * 
	 * String aa="(系统代码:wxt)内容包含敏感词 ：[法轮功, 法轮, 优惠]"; System.out.println(); }
	 */

	// MD5 加密函数
	public static String MD5Encode(String sourceString) {
		String resultString = null;
		try {
			resultString = new String(sourceString);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byte2hexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
		}
		return resultString;
	}

	public static final String byte2hexString(byte[] bytes) {
		StringBuffer bf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xff) < 0x10) {
				bf.append("0");
			}
			bf.append(Long.toString(bytes[i] & 0xff, 16));
		}
		return bf.toString();
	}

	/**
	 * 短信发送
	 * 
	 * @param msgid
	 *            自定义msgid，用户查询发送结果
	 * @param phone
	 *            发送号码(小于等于500)
	 * @param content
	 *            发送内容
	 */
	public static Map<String, Object> send(String msgid, String phone,
			String content) {
		String posturl = url + "/http/sms/Submit";
		Map<String, String> params = new LinkedHashMap<String, String>();
		HttpXmlUtil docXml = new HttpXmlUtil();
		String message = docXml.DocXml(userName, MD5Encode(password), msgid,
				phone, content, sign, subcode, sendtime);
		params.put("message", message);
		String resp = doPost(posturl, params);
		Map<String, Object> map = readSendStatus(resp);

		return map;
	}

	/**
	 * 获取发送状态报告
	 * 
	 * @return 返回状态报告map
	 */
	public static Map<String, Object> getReport() {
		String posturl = url + "/http/sms/Report";
		Map<String, String> params = new LinkedHashMap<String, String>();
		String message = "<?xml version='1.0' encoding='UTF-8'?><message>"
				+ "<account>" + userName + "</account>" + "<password>"
				+ MD5Encode(password) + "</password>"
				+ "<msgid></msgid><phone></phone></message>";
		params.put("message", message);
		String resp = doPost(posturl, params);
		return readReport(resp);
	}

	// 查询余额
	private static void getBalance() {
		String posturl = url + "/http/sms/Balance";
		Map<String, String> params = new LinkedHashMap<String, String>();
		String message = "<?xml version='1.0' encoding='UTF-8'?><message><account>"
				+ userName
				+ "</account>"
				+ "<password>"
				+ MD5Encode(password)
				+ "</password></message>";
		params.put("message", message);
		System.out.println(message);
		String resp = doPost(posturl, params);
		System.out.println(resp);
	}

	// 获取上行
	private static void getSms() {
		String posturl = url + "/http/sms/Deliver";
		Map<String, String> params = new LinkedHashMap<String, String>();
		String message = "<?xml version='1.0' encoding='UTF-8'?><message><account>"
				+ userName
				+ "</account>"
				+ "<password>"
				+ MD5Encode(password)
				+ "</password></message>";
		params.put("message", message);
		String resp = doPost(posturl, params);
		System.out.println(resp);
	}

	/**
	 * 执行一个HTTP POST 请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL 地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @return 返回请求响应的HTML
	 */
	private static String doPost(String url, Map<String, String> params) {
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(
				HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		// 设置Post 数据
		if (!params.isEmpty()) {
			int i = 0;
			NameValuePair[] data = new NameValuePair[params.size()];
			for (Entry<String, String> entry : params.entrySet()) {
				data[i] = new NameValuePair(entry.getKey(), entry.getValue());
				i++;
			}
			postMethod.setRequestBody(data);
		}
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				response = postMethod.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return response;
	}

	/**
	 * 使用document 对象封装XML
	 * 
	 * @param userName
	 * @param pwd
	 * @param id
	 * @param phone
	 * @param contents
	 * @param sign
	 * @param subcode
	 * @param sendtime
	 * @return
	 */
	public String DocXml(String userName, String pwd, String msgid,
			String phone, String contents, String sign, String subcode,
			String sendtime) {
		Document doc = DocumentHelper.createDocument();
		doc.setXMLEncoding("UTF-8");
		Element message = doc.addElement("message");
		Element account = message.addElement("account");
		account.setText(userName);
		Element password = message.addElement("password");
		password.setText(pwd);
		Element msgid1 = message.addElement("msgid");
		msgid1.setText(msgid);
		Element phones = message.addElement("phones");
		phones.setText(phone);
		Element content = message.addElement("content");
		content.setText(contents);
		Element sign1 = message.addElement("sign");
		sign1.setText(sign);
		Element subcode1 = message.addElement("subcode");
		subcode1.setText(subcode);
		Element sendtime1 = message.addElement("sendtime");
		sendtime1.setText(sendtime);
		return message.asXML();
		// System.out.println(message.asXML());
	}

	public static Map<String, Object> readResp(String str) {

		Map<String, Object> hashMap = new HashMap<String, Object>();

		try {

			Document document = DocumentHelper.parseText(str);
			Element root = document.getRootElement();
			Iterator<?> iter = root.elementIterator();

			while (iter.hasNext()) {
				Element el = (Element) iter.next();
				hashMap.put(el.getName(), el.getText());
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return hashMap;
	}

	/**
	 * 处理短信状态报告xml
	 * 
	 * @param str
	 * @return
	 * 
	 */
	public static Map<String, Object> readReport(String str) {

		System.out.println("返回信息：" + str);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> reportMap = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		try {

			Document document = DocumentHelper.parseText(str);
			Element root = document.getRootElement();
			// 获取调用结果，0为成功，其他状态不处理report
			Element result = root.element("result");
			Element desc = root.element("desc");
			// 放入请求结果
			resultMap.put("result", result.getText());

			if ("0".equals(result.getText())) {

				Iterator<?> iter = root.elementIterator("report");

				while (iter.hasNext()) {
					reportMap = new HashMap<String, Object>();

					Element el = (Element) iter.next();

					Element msgid = el.element("msgid");
					Element phone = el.element("phone");
					Element status = el.element("status");
					Element descs = el.element("desc");

					reportMap.put("msgid", msgid.getText());
					reportMap.put("phone", phone.getText());
					reportMap.put("status", status.getText());
					reportMap.put("desc", descs.getText());

					list.add(reportMap);
				}

			}

			resultMap.put("reportList", list);

		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 解析短信接口提交报告
	 * 
	 * @param str
	 * @return 0--提交成功 10——内容包含敏感词
	 */
	public static Map<String, Object> readSendStatus(String str) {

		System.out.println("返回提交信息：" + str);
		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {

			Document document = DocumentHelper.parseText(str);
			Element root = document.getRootElement();
			// 获取调用结果，0为成功，其他状态不处理report
			Element result = root.element("result");
			Element desc = root.element("desc");

			// 放入请求结果
			resultMap.put("result", result.getText());
			resultMap.put("desc", desc.getText());

		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 新房私客接口
	 * @param params
	 * @return
	 */
	public static Map<String, Object> getNCustomer(Map<String, String> params) {

		Map<String, Object> map = new HashMap<String, Object>();
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(
				"http://xf.qfang.com/customer/getNCustomer");
		postMethod.getParams().setParameter(
				HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		// 设置Post 数据
		if (!params.isEmpty()) {
			int i = 0;
			NameValuePair[] data = new NameValuePair[params.size()];
			for (Entry<String, String> entry : params.entrySet()) {
				data[i] = new NameValuePair(entry.getKey(), entry.getValue());
				i++;
			}
			postMethod.setRequestBody(data);
		}
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				response = postMethod.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			//标示http请求异常
			map.put("requestCode","00001");
		} finally {
			postMethod.releaseConnection();
		}

		if (null != response) {

			Map<String, Object> tempMap = null;
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			// 将json字符串转换为json对象
			JSONObject jsonObj;
			try {
				jsonObj = new JSONObject(response);

				// 得到指定json key对象的value对象
				String returnCode=jsonObj.getString("returnCode");
				map.put("returnCode",returnCode);
				map.put("total", jsonObj.getString("total"));
				map.put("records", jsonObj.getString("records"));
				map.put("desc", jsonObj.getString("desc"));
				map.put("page", jsonObj.getString("page"));

				if("00000".equals(returnCode)){
					
					JSONArray rows = jsonObj.getJSONArray("rows");
					// 遍历jsonArray
					for (int i = 0; i < rows.length(); i++) {
						// 获取每一个json对象
						tempMap = new HashMap<String, Object>();
						JSONObject jsonItem = rows.getJSONObject(i);

						tempMap.put("id", jsonItem.get("id"));
						tempMap.put("name", jsonItem.get("name"));
						tempMap.put("phone", jsonItem.get("phone"));

						list.add(tempMap);
					}
					map.put("rows", list);
					
				}else{
					
					//存入空的list
					map.put("rows", list);
				}
			

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//标示http请求异常
				map.put("requestCode","00001");
			}

		}
		return map;
	}

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("personId", "qBBo45uWQfmyUNSaWdhBGYDvfe0=");
		map.put("purporse", "BUY");
		map.put("Page", "1");
		map.put("pageSize", "50");
		Map map2 = getNCustomer(map);

		System.out.println(map2.get("returnCode"));
		System.out.println(map2.get("total"));
		System.out.println(map2.get("desc"));
		System.out.println(map2.get("records"));
		System.out.println(map2.get("page"));
		System.out.println(map2.get("rows"));

	}
}